package com.open.rbac.config;

import org.apache.catalina.Context;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * TLS安全增强配置
 *
 * @author Riche's
 * @since 2025/5/24
 */
@Configuration
public class TLSConfig {

    @Bean
    public TomcatServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new MeTomcatServletWebServerFactory();
        factory.addConnectorCustomizers(connector -> connector.setAllowTrace(true));
        return factory;
    }

    public static final class MeTomcatServletWebServerFactory extends TomcatServletWebServerFactory {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint constraint = new SecurityConstraint();
            constraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addMethod(DEFAULT_PROTOCOL);
            constraint.addCollection(collection);
            constraint.setAuthConstraint(true);
            context.addConstraint(constraint);
        }
    }

}
